package com.smartlight.godlight;

import static com.google.zxing.integration.android.IntentIntegrator.REQUEST_CODE;

import android.content.Context;
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.smartlight.godlight.adapter.BuddhaAdapter;
import com.smartlight.godlight.adapter.TimespanAdapter;
import com.smartlight.godlight.constant.GodlApi;
import com.smartlight.godlight.listener.OnItemClickListener;
import com.smartlight.godlight.model.AppInfo;
import com.smartlight.godlight.model.Buddha;
import com.smartlight.godlight.model.Fruit;
import com.smartlight.godlight.model.OrderInfo;
import com.smartlight.godlight.model.Timespan;
import com.smartlight.godlight.utils.OkHttpUtils;
import com.smartlight.godlight.utils.SharedPreferencesUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WorshipData extends AppCompatActivity {

    private final String TAG = "WorshipData";
    private OrderInfo orderInfo;
    // 数据对象
    private AppInfo appInfo;
    // 准备数据
    List<Fruit> mFruits = new ArrayList<>();

    @Override
    protected void  onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.worshipdata);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // 获取ActionBar对象（实际上是Toolbar）并设置属性
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true); // 显示返回箭头
            actionBar.setHomeAsUpIndicator(R.drawable.arrow_yellow); // 设置返回图标
            actionBar.setTitle("返回"); // 设置标题文字
        }

        // 设置Title
        setTitle();

        // 订单对象实例化
        orderInfo = new OrderInfo();

        // 加载数据
        loadData();
        // 刷新UI

        // 事件处理与监听
        // 点击添加祈福语
        Button addBlessingBtn = findViewById(R.id.addBlessingBtn);
        addBlessingBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(WorshipData.this, SelectSentence.class);
                startActivityForResult(intent, 1234);
            }
        });

        // 提交到支付确认页面
        Button submit_btn = findViewById(R.id.sbmit_btn);
        submit_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 校验数据是否正常
                EditText editname = findViewById(R.id.editname);
                EditText editphone = findViewById(R.id.editphone);
                TextView editblessing = findViewById(R.id.editblessing);
                if (editname.getText().toString().isEmpty()) {
                    Toast.makeText(WorshipData.this, "姓名不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (editphone.getText().toString().isEmpty()) {
                    Toast.makeText(WorshipData.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (orderInfo.getBuddhaName() == null || orderInfo.getBuddhaName().equals("")) {
                    Toast.makeText(WorshipData.this, "请选择佛像", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (editblessing.getText().toString().isEmpty()) {
                    Toast.makeText(WorshipData.this, "祈福不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (orderInfo.getTimespanName() == null || orderInfo.getTimespanName().equals("")) {
                    Toast.makeText(WorshipData.this, "请选择时长", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 构造订单信息
                orderInfo.setName(editname.getText().toString());
                orderInfo.setPhone(editphone.getText().toString());
                orderInfo.setBlessing(editblessing.getText().toString());
                Log.d(TAG ,"订单信息： " + orderInfo.toString());

                Intent submitIntent = new Intent();
                submitIntent.setClass(WorshipData.this,ScanPay.class);
                submitIntent.putExtra("orderInfo", orderInfo);
                startActivity(submitIntent);
            }
        });
    }

    private void setTitle() {
        if (SharedPreferencesUtils.getParam(this,"title", "") != ""){
            TextView title = findViewById(R.id.title);
            title.setText(SharedPreferencesUtils.getParam(this,"title", "").toString());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.d(TAG, "-关闭页面--");
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            // 处理佛灯页面返回的数据
            String buddhaNo = data.getStringExtra("buddha_light_no");
            Log.d(TAG, "客户选择了佛灯: " + buddhaNo);
            TextView chooselight = findViewById(R.id.choose_buddha_name);
            chooselight.setText("您选择了" + buddhaNo + "号佛灯");
            orderInfo.setBuddhaNo(buddhaNo);

        } else if (requestCode == 1234 && resultCode == RESULT_OK) {
            // 处理祈福语页面返回的数据
            String blessing = data.getStringExtra("blessing");
            Log.d(TAG, "客户选择了祈福语: " + blessing);
            TextView editblessing = findViewById(R.id.editblessing);
            editblessing.setText(blessing);
            orderInfo.setBlessing(blessing);
        }
    }

    private void loadData() {
        if (SharedPreferencesUtils.getParam(this, "appInfo", "") != ""){
            Object appInfoStr = SharedPreferencesUtils.getParam(this, "appInfo", "");
            JsonObject jsonObject = new Gson().fromJson((String) appInfoStr, JsonObject.class);
            Log.d(TAG, "-存在---读取数据---" + jsonObject.get("data").toString());
            appInfo = new Gson().fromJson(jsonObject.get("data").toString(), AppInfo.class);
            Log.d(TAG, "-存在---读取数据---" + appInfo.getTitle() + " :"  + appInfo.getBackgroundUrl());
            Log.d(TAG, "-存在---读取佛像数据---" + appInfo.getBuddhaList().size());
            // 刷新UI
            setBuddha();
            setTimeSpan();
        }else{
            OkHttpUtils.get(GodlApi.GET_APP_INFO, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    GodlApi.printLog(TAG, "接口:" + GodlApi.GET_APP_INFO + ", 请求失败, " + e.toString());
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    String data = response.body().string();
                    GodlApi.printLog(TAG, "接口:" + GodlApi.GET_APP_INFO + ", 请求成功, 返回数据：" + data);
                    Object appInfoStr = SharedPreferencesUtils.getParam(WorshipData.this, "appInfo", "");
                    JsonObject jsonObject = new Gson().fromJson(data, JsonObject.class);
                    Log.d(TAG, "----接口请求数据---" + jsonObject.get("data").toString());
                    appInfo = new Gson().fromJson(jsonObject.get("data").toString(), AppInfo.class);

                    // 刷新UI
                    setBuddha();
                    setTimeSpan();



                }
            });
        }
    }

    private void setTimeSpan() {
        TimespanAdapter timespanAdapter = new TimespanAdapter(WorshipData.this, appInfo.getTimeSpanList());
        RecyclerView timespanRecyclerView = findViewById(R.id.timespanRecycleView);
        timespanRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); // 设置布局管理器，例如线性布局管理
        timespanRecyclerView.setAdapter(timespanAdapter);

        // 点击
        timespanAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Timespan timespan = appInfo.getTimeSpanList().get(position);
                Log.d(TAG, "时长信息: " + timespan.toString());
                orderInfo.setTimespanId(timespan.getId());
                orderInfo.setTimespanName(timespan.getName());
                orderInfo.setMonth(timespan.getMonth());
                orderInfo.setMoney(timespan.getMoney());
            }
        });
    }

    private void setBuddha() {
        // 第二种方式: recyclerView
        BuddhaAdapter myAdapter = new BuddhaAdapter(WorshipData.this ,appInfo.getBuddhaList());
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); // 设置布局管理器，例如线性布局管理
        recyclerView.setAdapter(myAdapter); // 替换YourAdapter为你的适配器类

        myAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Buddha buddha = appInfo.getBuddhaList().get(position);

                // 设置选中佛灯信息
                orderInfo.setBuddhaId(buddha.getId());
                orderInfo.setBuddhaName(buddha.getName());
                orderInfo.setBuddhaImg(buddha.getImg());

                // 记录数据并传递到下一页
                Intent intent = new Intent();
                intent.setClass(WorshipData.this, SelectGod.class);
                intent.putExtra("buddha", buddha);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // 返回按钮被点击时执行的代码
                Toast.makeText(this, "返回按钮被点击", Toast.LENGTH_SHORT).show();
                finish();
                return true; // 表示事件已被处理，不再向上传递
        }
        return super.onOptionsItemSelected(item); // 对于其他菜单项，调用父类的处理方法
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (v instanceof EditText) {
                View w = getCurrentFocus();
                int[] coords = new int[2];
                w.getLocationOnScreen(coords);
                float x = ev.getRawX() + w.getLeft() - coords[0];
                float y = ev.getRawY() + w.getTop() - coords[1];
                if (x < w.getRight() && x > w.getLeft() && y < w.getBottom() && y > w.getTop())
                    return super.dispatchTouchEvent(ev); // 如果点击的是EditText，则不隐藏键盘
                else
                    hideKeyboard(v); // 如果点击的是EditText之外的地方，则隐藏键盘
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    public void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}
